﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace P2PWeb.Common
{
    public class MoneyRange : ValidationAttribute, IClientValidatable
    {
        private int _value;

        public MoneyRange(int value=100)
        {
            this._value = value;
        }

        public override bool IsValid(object value)
        {
            int money = Convert.ToInt32(value);
            return money % _value == 0 && money > 0;
        }

        public override string FormatErrorMessage(string name)
        {
            string message= string.Format("{0}必须是{1}的倍数并且大于0",name,_value);
            return message;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
             ModelClientValidationRule validationRule =
                 new ModelClientValidationRule() { ValidationType = "moneyrange", ErrorMessage = FormatErrorMessage(metadata.DisplayName) };
             validationRule.ValidationParameters.Add("rangevalue", _value);
           yield return validationRule;
        }
    }
}